package com.itheima.search.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * RabbitMQ配置类，主要配置消息转换器以支持Java 8日期类型
 * @author NicelYHHello
 */
@Configuration
public class RabbitMQConfig {

    // 消息中日期时间的格式（与实际消息格式保持一致）
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 配置Jackson消息转换器，支持LocalDateTime等Java 8日期类型
     */
    @Bean
    public Jackson2JsonMessageConverter jsonMessageConverter() {
        // 创建ObjectMapper实例
        ObjectMapper objectMapper = new ObjectMapper();

        // 注册JavaTimeModule以支持Java 8日期类型
        JavaTimeModule javaTimeModule = new JavaTimeModule();

        // 自定义LocalDateTime的序列化和反序列化格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT);
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));

        objectMapper.registerModule(javaTimeModule);

        // 配置全局日期格式（针对java.util.Date等旧日期类型）
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));

        // 忽略未知字段，避免消息结构变化导致解析失败
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 创建并返回消息转换器
        return new Jackson2JsonMessageConverter(objectMapper);
    }

    /**
     * 配置RabbitMQ监听容器工厂，关联自定义的消息转换器
     */
    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
            ConnectionFactory connectionFactory,
            Jackson2JsonMessageConverter jsonMessageConverter) {

        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        // 设置连接工厂
        factory.setConnectionFactory(connectionFactory);
        // 关联消息转换器（关键：确保监听者使用我们配置的转换器）
        factory.setMessageConverter(jsonMessageConverter);

        // 可选配置：设置并发消费者数量
        factory.setConcurrentConsumers(1);
        factory.setMaxConcurrentConsumers(5);

        return factory;
    }
}
